<?php

namespace app\index\controller;

use QL\QueryList;
use think\Controller;
use think\Request;
use ZipArchive;

class Index extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    /** 爬取图片
     * @return \think\response\Download
     */
    public function grasp()
    {
        cache('list',null);
        cache('fileList',null);
        $postData = $this->request->post('data');
        // 开始页数
        $i = 1;
        // 抓取到的文件地址
        $list = [];
        $time = time();
        // 目录
        $path = "./static/$time";
        $zipPtah = "./static/$time.zip";
        while ($i <= $postData['page']) {
            $url = "https://you.ctrip.com/destinationsite/TTDSecond/SharedView/AsynCommentView";

//            $post = [
//                'poiID' => 95355,
//                'districtId' => 120478,
//                'districtEName' => 'Seda',
//                'pagenow' => $i,
//                'order' => 1,
//                'star' => 0.0,
//                'tourist' => 0.0,
//                'resourceId' => 133401,
//                'resourcetype' => 2
//            ];

            $post = [
                'poiID' => $postData['poiID'],
                'districtId' => $postData['districtId'],
                'districtEName' => $postData['districtEName'],
                'pagenow' => $i,
                'order' => 1,
                'star' => 0.0,
                'tourist' => 0.0,
                'resourceId' => $postData['resourceId'],
                'resourcetype' => 2
            ];
            $rules = [
                'img' => ['.comment_piclist>a', 'href'],
            ];
            $data = QueryList::post($url, $post)->rules($rules)->query()->getData();

            $img = $data->all();
            $imgList = array_column($img, 'img');
            foreach ($imgList as $v) {
                $list[] = $v;
            }
            $i++;

        }

        // 返回参数
        $count = count($list);
        if ($count > 0) {
            // 分隔成数组、并且储存图片信息
            cache('list',json_encode(array_chunk($list,10)));
            $data = [
                'code' => 1,
                'msg' => '抓取完成，共' . count($list) . '张图片,开始下载图片',
                'data'=>[
                    'path'=>$path,
                    'time'=>$time,
                    'zipPath'=>$zipPtah,
                    'count'=>count(json_decode(cache('list'),true))
                ]
            ];
        }else{
            $data = [
                'code' => 0,
                'msg' => '抓取失败',
            ];
        }
        return json_encode($data);

    }

    /**
     * 保存图片
     */
    public function save()
    {
        $postData = $this->request->post('data');

        // 当前份数
        $number = $this->request->post('number');

        //创建文件夹
        if (!is_dir($postData['path'])) {
            mkdir($postData['path'], 0777, true);
        }

        // 文件相对路径
        $fileList = [];
        $list = json_decode(cache('list'),true);
        //循环保存文件到指定目录
        foreach ($list[$number] as $k => $v) {
            $savePath = "{$postData['path']}/$k"."$number.jpg";

            // 检查文件是否有效
            if (strlen(file_get_contents($v)) != 0) {
                $fileList[] = $savePath;
                file_put_contents($savePath, file_get_contents($v));
            }

        }
        // 储存文件地址
        $arrCache = cache('fileList');
        if($arrCache){
            $jsonArr = json_decode($arrCache,true);
            //追加
            $arr = array_merge($jsonArr,$fileList);
        }else{
            $arr = $fileList;
        }
        cache('fileList',json_encode($arr));
        // 返回百分比
        $data = [
            'code'=>1,
            'msg'=>'',
            'data'=>''
        ];

        return json_encode($data);
    }

    /**
     * 解压图片，并且返回下载地址
     */
    public function download()
    {
        $postData = $this->request->post('data');

        $zip = new \ZipArchive();

        //创建zip文件
        $zip->open($postData['zipPath'], ZIPARCHIVE::CREATE);
        $fileList = json_decode(cache('fileList'),true);
        foreach ($fileList as $v) {
            // 循环遍历文件放入压缩文件夹中
            if (file_exists($v)) {
                $zip->addFile($v, basename($v));
            }
        }

        // 关闭zip函数
        $zip->close();
        //return download($postData['zipPath'], "{$postData['time']}.zip");
        $data = [
            'code'=>1,
            'msg'=>'',
            'data'=>'http://localhost/static/'.$postData['time'].'.zip'
        ];

        return json_encode($data);
    }

}
